package com.hncboy.chatgpt.front.handler;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hncboy.chatgpt.base.handler.response.ResultCode;
import com.hncboy.chatgpt.base.util.ObjectMapperUtil;
import com.hncboy.chatgpt.base.util.WebUtil;
import com.hncboy.chatgpt.front.domain.request.ChatProcessRequest;
import com.hncboy.chatgpt.front.domain.vo.ChatReplyMessageVO;
import com.hncboy.chatgpt.front.service.KeyService;
import com.mysql.cj.protocol.MessageSender;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.PrintWriter;
import java.time.Duration;
import java.util.concurrent.Executors;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private KeyService keyService;

    @Autowired
    private ObjectMapper objectMapper;
    private ResponseBodyEmitter emitter;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = WebUtil.getIp();
        String userKey = stringRedisTemplate.opsForValue().get(ip);

        if (userKey == null) {
            // 新用户
            userKey = keyService.getKey(ip, 200);
            stringRedisTemplate.opsForValue().set(ip, userKey);
        } else {
            // 老用户
            String limitKey = ip;
            String limitip = stringRedisTemplate.opsForValue().get(limitKey);
            String limitValue = stringRedisTemplate.opsForValue().get(limitip);
            if (limitValue == null) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return false;
            }
            // 从 Redis 中获取对应的 JSON 字符串
            String value = stringRedisTemplate.opsForValue().get(limitip);

            // 将 JSON 字符串解析为 JsonNode 对象
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(value);
            int usageCount = jsonNode.get("usageCount").asInt();

            if (usageCount == 0) {
//                response.sendError(HttpServletResponse.SC_FORBIDDEN, "使用次数已用完，请支付");
                ChatReplyMessageVO chatReplyMessageVO = ChatReplyMessageVO.onEmitterChainException((ChatProcessRequest) request);
                chatReplyMessageVO.setText(StrUtil.format("Key使用次数已用完，请支付"));
                emitter.send(ObjectMapperUtil.toJson(chatReplyMessageVO));
                emitter.complete();
                return false;
            }

            // 更新 usageCount 字段的值
            ((ObjectNode) jsonNode).put("usageCount", usageCount - 1);

            // 将更新后的 JSON 对象重新写回 Redis 中
            stringRedisTemplate.opsForValue().set(limitip, jsonNode.toPrettyString());
        }

        // 将用户信息存入请求对象中
        request.setAttribute("ip", ip);
        request.setAttribute("userKey", userKey);

        // 继续处理业务逻辑
        return true;
    }
}
